<template>
  <div class="pageOut">
    <div class="pageIn">
      <el-form :inline="true" :model="formSearch" size="small">
        <el-form-item>
          <el-date-picker
            v-model="formSearch.time"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="formSearch.shopName"
            placeholder="请输入广告名"
            clearable
          ></el-input>
        </el-form-item>
        <!-- 
        <el-form-item>
          <el-select
            v-model="formSearch.class_id"
            clearable
            filterable
            placeholder="分类"
            style="width: 250px"
          >
            <el-option label="邮寄" value="1"></el-option>
            <el-option label="自取" value="2"></el-option>
            <el-option label="点位自购" value="3"></el-option>
          </el-select>
        </el-form-item> -->

        <el-form-item>
          <el-button icon="el-icon-search" @click="search">查询</el-button>
          <el-button
            icon="el-icon-plus"
            type="primary"
            @click="handleAdd"
            v-if="permission.add"
            >添加</el-button
          >
        </el-form-item>
      </el-form>
      <el-table
        border
        ref="table"
        :height="height - 170"
        :data="tableData"
        :header-cell-style="{ background: '#FAFAFA', color: '#606266' }"
        v-loading="loading"
        element-loading-background="rgba(255, 255, 255, 0.5)"
        style="width: 100%"
      >
        <el-table-column prop="advertName" label="广告名"></el-table-column>
        <el-table-column prop="create_time" label="添加时间"></el-table-column>

        <el-table-column prop="pictures" label="广告详情">
          <template slot-scope="scope">
            <el-link type="primary" @click="handleEdit(scope.row, 'view')"
              >点击查看</el-link
            >
          </template>
        </el-table-column>
        <el-table-column prop="deviceNumber" label="显示设备">
          <template slot-scope="scope">
            <el-link type="primary" @click="getGoodsSel(scope.row.id)">{{
              scope.row.deviceNumber
            }}</el-link>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="300" align="center">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              @click="handleEdit(scope.row, 'edit')"
              v-if="permission.edit"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="mini"
              @click="handleDel(scope.row.id)"
              v-if="permission.del"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="pageSizes"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>

        <!-- 设备弹窗 -->
        <el-dialog
          :visible.sync="devicVisble"
          @close="dialogSearchClose"
          width="40%"
        >
          <el-form :inline="true" :model="dialogSearch" size="small">
            <el-form-item>
              <el-input
                v-model="dialogSearch.name"
                placeholder="设备名称"
                clearable
                @clear="getGoodsSel('sea')"
              ></el-input>
            </el-form-item>

            <el-form-item>
              <el-button icon="el-icon-search" @click="getGoodsSel('sea')"
                >查询</el-button
              >
            </el-form-item>
          </el-form>
          <el-table
            ref="multipleTable"
            :data="cleckData"
            tooltip-effect="dark"
            style="width: 100%"
            height="500"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55"> </el-table-column>

            <el-table-column
              prop="deviceCode"
              label="设备编号"
              show-overflow-tooltip
            >
            </el-table-column>

            <el-table-column
              prop="deviceName"
              label="设备名"
              show-overflow-tooltip
            >
            </el-table-column>

            <el-table-column
              prop="selfName"
              label="设备属性"
              show-overflow-tooltip
            >
            </el-table-column>

            <el-table-column
              prop="merchantName"
              label="商户名称"
              show-overflow-tooltip
            >
            </el-table-column>
            <el-table-column
              prop="address"
              label="设备地址"
              show-overflow-tooltip
            >
            </el-table-column>
          </el-table>
          <!-- <div class="pageBox">
            <el-pagination
              @current-change="dailogHandleSizeChange"
              background
              layout="prev, pager, next"
              :total="dialogTotal"
            >
            </el-pagination>
          </div> -->
          <span slot="footer" class="dialog-footer">
            <el-button @click="devicVisble = false">取 消</el-button>
            <el-button type="primary" @click="clickCheck">确 定</el-button>
          </span>
        </el-dialog>

        <!-- 显示设备 -->
        <el-dialog append-to-body :visible.sync="devicVisbleCopy" width="30%">
          <el-table
            ref="multipleTable"
            :data="cleckData"
            tooltip-effect="dark"
            style="width: 100%"
          >
            <el-table-column
              prop="deviceCode"
              label="设备编号"
              show-overflow-tooltip
            >
            </el-table-column>

            <el-table-column
              prop="deviceName"
              label="设备名"
              show-overflow-tooltip
            >
            </el-table-column>

            <el-table-column
              prop="selfName"
              label="设备属性"
              show-overflow-tooltip
            >
            </el-table-column>
          </el-table>
          <div class="pageBox">
            <el-pagination
              @current-change="dailogHandleSizeChange"
              background
              layout="prev, pager, next"
              :total="dialogTotal"
            >
            </el-pagination>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="devicVisbleCopy = false">取 消</el-button>
          </span>
        </el-dialog>

        <!-- 设备添加和商家编辑 -->
        <el-dialog
          width="65%"
          :title="title"
          :visible.sync="visible"
          @close="onCancel('ruleForm')"
          custom-class="custom_drawer"
        >
          <el-form
            :disabled="type == 'view'"
            :model="ruleForm"
            :rules="rules"
            ref="ruleForm"
            label-width="90px"
            size="mini"
          >
            <el-form-item
              label="广告名称"
              prop="name"
              style="margin-bottom: 30px"
            >
              <el-input
                style="width: 300px"
                type="text"
                clearable
                v-model="ruleForm.name"
                placeholder="请输入广告名称"
              ></el-input>
            </el-form-item>
            <el-form-item label="排序" prop="sort" style="margin-bottom: 30px">
              <el-input
                style="width: 300px"
                type="text"
                oninput="this.value=this.value.replace(/[^\d]/g,'')"
                clearable
                v-model="ruleForm.sort"
                placeholder="请输入排序"
              ></el-input>
            </el-form-item>
            <el-form-item label="选择设备" style="margin-bottom: 30px">
              <el-button type="primary" @click="clickDevic"
                >选择显示设备</el-button
              >
            </el-form-item>
            <div>
              <el-tag
                v-for="(tag, tagIndex) in goodsRow"
                @close="closeTag(tagIndex, tag)"
                :key="tagIndex"
                closable
                style="margin-right: 10px"
              >
                <span class="tagBox">{{ tag.deviceName }}</span>
              </el-tag>
            </div>
            <div class="tableHeader flexRow">
              <span>顺序</span>
              <span>广告图/视频</span>
              <span>关联内容链接</span>
              <span>关联内容</span>
              <span>操作</span>
            </div>
            <draggable
              class="syllable_ul"
              element="ul"
              :list="ruleForm.advertArr"
              :options="{ group: 'starCoachList', animation: 150 }"
              :no-transition-on-drag="true"
              @change="change"
              @start="start"
              @end="end"
              :move="move"
            >
              <transition-group type="transition" name="拖拽" :css="true">
                <div
                  class="flexRow"
                  v-for="(item, index) in ruleForm.advertArr"
                  :key="index"
                >
                  <span style="margin-top: -13px">第{{ index + 1 }}张</span>
                  <Upload
                    style="margin-left: 45px"
                    @getImgSrc="getImgSrc"
                    :index="index"
                    :imageUrl.sync="item.mainPicture"
                    ref="image"
                  />
                  <div>
                    <el-form-item
                      :prop="'advertArr.' + index + '.linkType'"
                      :rules="{
                        required: true,
                        message: '请选择类别',
                        trigger: 'change',
                      }"
                    >
                      <el-select
                        style="width: 150px"
                        clearable
                        v-model="item.linkType"
                        placeholder="请选择"
                      >
                        <el-option label="商品" value="1"> </el-option>
                      </el-select>
                    </el-form-item>
                  </div>
                  <div class="flexComiBox" v-if="item.commiData.id">
                    <div class="flexComi">
                      <img
                        :src="item.commiData.mainPicture"
                        width="40px"
                        height="40px"
                        alt=""
                      />
                      <span class="textTherr">{{ item.commiData.name }}</span>
                    </div>
                    <el-link
                      v-if="type == 'add' || type == 'edit'"
                      type="primary"
                      style="margin-top: 5px"
                      @click="getGoodsSelCommi(index)"
                      >重新选择</el-link
                    >
                  </div>
                  <div class="flexComi" v-else>
                    <el-button
                      style="margin-left: 20px"
                      type="primary"
                      @click="getGoodsSelCommi(index)"
                      >选择商品</el-button
                    >
                  </div>

                  <span
                    v-if="type == 'add' || type == 'edit'"
                    style="margin-top: -13px; color: red"
                    @click="delPitch(index)"
                    >删除</span
                  >
                  <span v-else></span>
                </div>
              </transition-group>
            </draggable>
            <el-button @click="addPitch" style="margin-top: 30px" type="primary"
              >添加一组</el-button
            >
          </el-form>

          <div slot="footer">
            <el-button @click="visible = false" size="small">取 消</el-button>
            <el-button
              :disabled="type == 'view'"
              type="primary"
              size="small"
              @click="onConfirm('ruleForm')"
              :loading="confirmLoading"
              >{{ confirmLoading ? "提交中 ..." : "确 定" }}</el-button
            >
          </div>
        </el-dialog>

        <el-dialog title="选择产品" :visible.sync="goodsDialog" width="35%">
          <el-form :inline="true" :model="dialogSearchCommi" size="small">
            <el-form-item>
              <el-cascader
                v-model="dialogSearchCommi.merchant_id"
                :props="casProps"
                :options="casOptions"
                clearable
              ></el-cascader>
            </el-form-item>
            <el-form-item>
              <el-input
                v-model="dialogSearchCommi.name"
                placeholder="商品名称"
                clearable
                @clear="getGoodsSelCommi"
              ></el-input>
            </el-form-item>

            <el-form-item>
              <el-button icon="el-icon-search" @click="getGoodsSelCommi"
                >查询</el-button
              >
            </el-form-item>
          </el-form>
          <el-table
            ref="multipleCommiTable"
            :data="cleckDataCommi"
            tooltip-effect="dark"
            style="width: 100%"
            height="500"
            @selection-change="handleSelectionChangeCommi"
          >
            <el-table-column type="selection" width="55"> </el-table-column>

            <el-table-column label="图片">
              <template slot-scope="scope">
                <img
                  :src="scope.row.mainPicture"
                  style="width: 40px"
                  height="40px"
                  alt=""
                />
              </template>
            </el-table-column>
            <el-table-column prop="name" label="商品名称" show-overflow-tooltip>
            </el-table-column>
            <el-table-column
              prop="sellingPrice"
              label="价格"
              show-overflow-tooltip
            >
            </el-table-column>
          </el-table>
          <!-- <div class="pageBox">
            <el-pagination
              @size-change="dailogHandleSizeChangeCommi"
              background
              layout="prev, pager, next"
              :total="dialogTotalCommi"
            >
            </el-pagination>
          </div> -->
          <span slot="footer" class="dialog-footer">
            <el-button @click="goodsDialog = false">取 消</el-button>
            <el-button type="primary" @click="goodsSave">确 定</el-button>
          </span>
        </el-dialog>
      </div>
    </div>
  </div>
</template>
<script>
import {
  advertList,
  advertAdd,
  advertEdit,
  advertDel,
  advertInfo,
  advertDevices,
  MAIN,
  typeList,
  goodsSel,
} from "../../utils/api";
import draggable from "vuedraggable";
import Upload from "../../components/Upload";
export default {
  name: "Advertising",
  props: ["height"],
  components: {
    Upload,
    draggable,
  },
  data() {
    return {
      formSearch: {
        time: "",
        shopName: "",
        class_id: "",
      },
      title: "添加",
      goodsIndx: "",
      type: "",
      commiRow: [],
      infoData: {},
      casOptions: [],
      cleckData: [],
      dialogTotalCommi: 0,
      doaPageNumberCommi: 1,
      devicVisbleCopy: false,
      cleckDataCommi: [],
      confirmLoading: false,
      dialogTotal: 0,
      casProps: {
        value: "id",
        label: "name",
        children: "child",
      },
      rules: {
        name: [{ required: true, message: "输入广告名字", trigger: "blur" }],
        sort: [{ required: true, message: "输入排序", trigger: "blur" }],
      },
      ruleForm: {
        objectId: "",
        name: "",
        mainPicture: "",
        linkType: "",
        sort: "",
        advertArr: [
          {
            mainPicture: "",
            objectId: "",
            linkType: "",
            commiData: {},
          },
        ],
      },
      dialogSearchCommi: {
        name: "",
        merchant_id: "",
      },
      tableData: [],
      goodsDialog: false,
      loading: true, //显示加载表格
      goodsRow: [],
      currentPage: 1,
      pageSizes: [10, 20, 30, 40, 50], //每页选择条数
      pageSize: 10,
      total: 0,
      userInfo: {},
      visible: false,
      devicVisble: false,
      doaPageNumber: 1,
      dialogSearch: {
        name: "",
      },
      permission: {
        add: false,
        edit: false,
        del: false,
      }, //权限
    };
  },
  created() {
    const userinfo = JSON.parse(sessionStorage.getItem("userInfo")); //解密,获取用户登录信息
    this.userInfo = userinfo;
    this.userInfo = userinfo;
    let arr = userinfo.menu_id.split(",");

    // console.log(arr)
    // 添加广告 102
    // 编辑广告 103
    // 删除 104

    if (arr.indexOf("102") > -1) {
      this.permission.add = true;
    }
    if (arr.indexOf("103") > -1) {
      this.permission.edit = true;
    }

    if (arr.indexOf("104") > -1) {
      this.permission.del = true;
    }

    this.getData();
    this.cateSelects();
    this.getGoodsSel();
  },
  methods: {
    clickDevic() {
      this.devicVisble = true;
      // this.getGoodsSel("sea");

      // console.log(this.goodsRow);
      setTimeout(() => {
        this.goodsRow.map((v) => {
          this.$refs.multipleTable.toggleRowSelection(v, true);
        });
      }, 300);
    },
    // 商品分类列表
    cateSelects() {
      this.postRequest(typeList, MAIN).then((res) => {
        if (res.code == 200) {
          this.casOptions = res.data;
        }
      });
    },
    // 设备标签删除
    closeTag(index, item) {
      this.goodsRow.splice(index, 1);
      this.$refs.multipleTable.toggleRowSelection(item, false);
    },
    addPitch() {
      this.ruleForm.advertArr.push({
        mainPicture: "",
        objectId: "",
        linkType: "",
        commiData: {},
      });
    },
    // 拖拽
    change(evt) {},
    start(evt) {},
    end(evt) {},
    move(evt) {},
    //新增
    handleAdd() {
      // console.log(this.commiRow);
      this.type = "add";
      this.currentRow = {};
      this.visible = true;
      this.title = "添加";
    },
    //编辑
    handleEdit(row, type) {
      this.type = type;
      if (type == "view") {
        this.title = "广告详情";
      } else {
        this.title = "编辑";
      }
      this.currentRow = row;
      this.visible = true;
      this.goodsRow = [];
      this.postRequest(advertInfo, { id: row.id }, MAIN).then((res) => {
        if (res.code === 200) {
          this.infoData = res.data;
          this.ruleForm = {
            deviceIds: res.data.deviceIds,
            objectId: "",
            name: res.data.advertName,
            mainPicture: "",
            linkType: "",
            sort: res.data.sort,
            advertArr: res.data.details,
          };
          res.data.devices.forEach((v) => {
            let index = this.cleckData.findIndex((v2) => {
              return v == v2.id;
            });
            if (index != -1) {
              this.goodsRow.push(this.cleckData[index]);
            }
            // 让设备反选
          });
        }
      });
    },
    //查询
    search() {
      this.getData();
    },
    dialogSearchClose() {
      this.dialogSearch = {
        name: "",
      };
    },
    // 获取广告设备列表
    getGoodsSel(id) {
      let params = {
        nameOrCode: this.dialogSearch.name,
        pageSize: 500,
        pageNumber: this.doaPageNumber,
      };
      if (id && id != "sea") {
        this.devicVisbleCopy = true;
        params.advertId = id;
      }
      // console.log(id);
      this.postRequest(advertDevices, params, MAIN).then((res) => {
        if (res.code === 200) {
          this.cleckData = res.data.list;
          this.dialogTotal = res.data.count;
        }
      });
    },
    // 商品列表
    getGoodsSelCommi(index) {
      // 广告栏索引
      let deviceIds = [];
      this.goodsRow.forEach((v) => {
        deviceIds.push(v.id);
      });
      this.goodsIndx = index;
      this.goodsDialog = true;
      let goodsId = "";
      if (this.type != "add") {
        goodsId = this.ruleForm.advertArr[index].commiData.id;
      }
      let params = {
        name: this.dialogSearchCommi.name,
        goodsTypeTwo: this.dialogSearchCommi.merchant_id[1] || "",
        pageSize: 10,
        pageNumber: this.doaPageNumberCommi,
        deviceIds: deviceIds.join(","),
      };
      this.postRequest(goodsSel, params, MAIN).then((res) => {
        if (res.code === 200) {
          this.cleckDataCommi = res.data.list;
          this.dialogTotalCommi = res.data.count;
          let selectGoodsId = this.cleckDataCommi.findIndex((v) => {
            return goodsId == v.id;
          });

          setTimeout(() => {
            this.$refs.multipleCommiTable.toggleRowSelection(
              this.cleckDataCommi[selectGoodsId],
              true
            );
          }, 200);
        }
      });
    },
    onCancel(ruleForm) {
      this.$refs[ruleForm].resetFields();
      this.goodsRow = [];
      this.commiRow = [];
      this.ruleForm = {
        objectId: "",
        name: "",
        sort: "",
        mainPicture: "",
        linkType: "",
        advertArr: [
          {
            mainPicture: "",
            objectId: "",
            linkType: "",
            commiData: {},
          },
        ],
      };
      this.$refs.multipleTable.clearSelection();
    },
    // devicVisble
    clickCheck() {
      // console.log(this.goodsRow);
      if (this.goodsRow.length != 0) {
        this.devicVisble = false;
      } else {
        this.$notify.error("请至少选择一个设备");
      }
    },
    dailogHandleSizeChange(val) {
      this.doaPageNumber = val;
      this.getGoodsSel();
    },
    dailogHandleSizeChangeCommi(val) {
      this.doaPageNumberCommi = val;
      this.getGoodsSelCommi();
    },
    //分页
    //分页
    handleSizeChange(val) {
      //每页 ${val} 条
      this.pageSize = val;
      this.getData();
    },
    handleCurrentChange(val) {
      //当前页
      this.currentPage = val;
      this.getData();
    },
    // 添加广告
    onConfirm(ruleForm) {
      // if(this.ruleForm.advertArr.length)
      this.$refs[ruleForm].validate((valid) => {
        if (valid) {
          this.confirmLoading = true;

          let arr = [];
          arr = this.ruleForm.advertArr;
          let num = 1;
          arr.map((v) => {
            v.sort = num++;
            v.objectId = v.commiData.id;
            v.linkType = "1";
          });
          let devicIds = [];
          if (this.goodsRow.length == 0) {
            this.$notify.error("请至少选择一个设备");
            this.confirmLoading = false;
            return;
          } else {
            this.goodsRow.forEach((v) => {
              devicIds.push(v.id);
            });
          }
          let params = {
            advertName: this.ruleForm.name,
            userId: this.userInfo.id,
            devices: devicIds.join(","),
            detail: this.ruleForm.advertArr,
            sort: this.ruleForm.sort,
          };
          // console.log(params);
          if (this.type == "add") {
            this.postRequest(advertAdd, params, MAIN).then((res) => {
              if (res.code === 200) {
                this.$notify.success(res.msg);
                this.visible = false;
                this.type = "";
                this.getData();
              }

              this.confirmLoading = false;
            });
          } else {
            params.id = this.currentRow.id;
            this.postRequest(advertEdit, params, MAIN).then((res) => {
              if (res.code === 200) {
                this.$notify.success(res.msg);
                this.visible = false;
                this.type = "";
                this.getData();
              }

              this.confirmLoading = false;
            });
          }
        } else {
          return false;
        }
      });
    },
    // 删除广告栏
    delPitch(index) {
      this.ruleForm.advertArr.splice(index, 1);
    },
    //获取初始数据
    getData() {
      this.loading = true;
      let start_time, end_time;
      if (this.formSearch.time != "" && this.formSearch.time != null) {
        start_time = this.formSearch.time[0] + " 00:00:00";
        end_time = this.formSearch.time[1] + " 23:59:59";
      }
      let params = {
        advertName: this.formSearch.shopName,
        start_time,
        end_time,
        pageNumber: this.currentPage,
        pageSize: this.pageSize,
      };
      this.postRequest(advertList, params, MAIN).then((res) => {
        if (res.code == 200) {
          this.tableData = res.data.list;
          this.total = res.data.count;
          this.loading = false;
          this.$nextTick(() => {
            //避免表格表头样式错乱
            if (this.$refs.table) this.$refs.table.doLayout();
          });
        }
      });
    },
    // 设备表格选择
    handleSelectionChange(selection) {
      this.goodsRow = selection;
    },
    // 商品保存
    goodsSave() {
      this.goodsDialog = false;
      this.ruleForm.advertArr[this.goodsIndx].commiData = this.commiRow[0];
    },
    // 商品表格选择
    handleSelectionChangeCommi(selection) {
      this.commiRow = selection;
      if (selection.length > 1) {
        let del_row = selection.shift();
        this.$refs.multipleCommiTable.toggleRowSelection(del_row, false);
      }
    },
    //删除
    handleDel(id) {
      let parm = {
        id: id,
        userId: this.userInfo.id,
      };
      this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.postRequest(advertDel, parm, MAIN).then((res) => {
            // console.log(res);
            if (res.code == 200) {
              this.$notify({
                title: "成功",
                message: res.msg,
                type: "success",
              });
              this.getData();
            }
          });
        })
        .catch(() => {});
    },
    // 商品主图
    getImgSrc(e, index) {
      this.ruleForm.advertArr[index].mainPicture = e;
    },
    //    if (this.$refs.image)
    //  this.$refs.image.clear();
  },
};
</script>
<style scoped>
.tableHeader {
  font-size: 20px;
  font-weight: bold;
}
.flexRow {
  display: flex;
  width: 90%;
  justify-content: space-between;
  padding: 0px 30px;
  align-items: center;
  margin-top: 30px;
}
.flexRow span {
  font-size: 18px;
  font-weight: bold;
}
.flexComi {
  display: flex;
  align-items: center;
  width: 145px;
  line-height: 20px;
}
.flexComi span {
  font-size: 14px;
  font-weight: normal;
  margin-left: 7px;
}
.pageBox {
  margin-top: 20px;
}
.flexComiBox {
  display: flex;
  flex-direction: column;
}
.tagBox {
  display: inline-block;
  max-width: 150px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.el-tag /deep/ .el-icon-close {
  top: -11px;
}
.textTherr {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3; /*想省略几行就写几*/
  -webkit-box-orient: vertical;
}
</style>
